package com.netty.rpc.reference;

import com.netty.rpc.RpcRequest;
import com.netty.rpc.RpcResponse;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

public class RpcServiceProxy {

    public static Object createProxy(ReferenceConfig referenceConfig) {
        return Proxy.newProxyInstance(
                RpcServiceProxy.class.getClassLoader(),  //本类的名称，
                new Class[]{referenceConfig.getServiceInterfaceClass()}, //新接口类的名称
                new ServiceProxyInvocationHandler(referenceConfig) //代理的handler
        );
    }

    static class ServiceProxyInvocationHandler implements InvocationHandler {

        private ReferenceConfig referenceConfig;

        public ServiceProxyInvocationHandler(ReferenceConfig referenceConfig) {
            this.referenceConfig = referenceConfig;
        }

        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //clentrpc 调用connet 方法
            NettyRpcClient nettyRpcClient = new NettyRpcClient(referenceConfig);
            nettyRpcClient.connect();

            //进行参数的封装rpcrequest的封装
            RpcRequest rpcRequest = new RpcRequest();
            rpcRequest.setRequestId(UUID.randomUUID().toString().replace("-", ""));
            rpcRequest.setServiceInterfaceClass(referenceConfig.getServiceInterfaceClass().getName());
            rpcRequest.setMethodName(method.getName());
            rpcRequest.setParameterTypes(method.getParameterTypes());
            rpcRequest.setArgs(args);

            //rpcresponse 进行removeCall进行回调
            RpcResponse rpcResponse = nettyRpcClient.remoteCall(rpcRequest);

            return rpcResponse.getResult();
        }
    }

}
